import * as assign from 'object-assign';

export default function serverDispatch(next) {
  return (reducer, initialState) => {
    const store = next(reducer, initialState);

    return assign({}, store, {
      dispatch: action => {
        store.dispatch(action);

        const patches = action.payload && action.payload.patches;
        patches && setTimeout(() => Object.keys(patches).forEach(type => {
          store.dispatch({
            type,
            payload: patches[type]
          })
        }), 4);

        return action;
      }
    });
  };
}
